package de.gebauer.xbmc;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

import de.gebauer.xbmc.utils.FileUtils;

public class VersionStripper {

	private static final String MAVEN_VERSION_PATTERN_STRING = "(.*)-(\\d\\.)*(\\d)(-SNAPSHOT)*$";
	private static final Pattern MAVEN_VERSION_PATTERN = Pattern
			.compile(MAVEN_VERSION_PATTERN_STRING);

	private static class ArgsBean {

		@Option(name = "-a", required = true)
		private File addonsDir;

	}

	public static void main(String[] args) {

		try {

			ArgsBean bean = new ArgsBean();
			new CmdLineParser(bean).parseArgument(args);

			new VersionStripper().run(bean.addonsDir);

		} catch (CmdLineException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void run(File addonsDir) throws IOException {
		System.out.println("Processing directory "
				+ addonsDir.getCanonicalPath());
		boolean processed = false;
		for (File file : addonsDir.listFiles()) {
			if (file.isDirectory()) {
				final String fileName = file.getName();
				final Matcher matcher = MAVEN_VERSION_PATTERN.matcher(fileName);
				if (matcher.matches()) {
					processed = true;
					final String group = matcher.group(1);
					final File newAddonDir = new File(addonsDir, group);

					if (newAddonDir.exists()) {
						System.out.println("Deleting directory " + group);
						if (!FileUtils.deleteRecursively(newAddonDir)) {
							System.out.println("Unable to delete " + fileName);
						}
					}

					System.out.println("Renaming " + fileName + " to " + group);
					final boolean success = file.renameTo(newAddonDir);
				}
			}
		}
		if (!processed) {
			System.out
					.println("No versions stripped from any directories / files");
		}
	}
}
